package com.isunland.managesystem.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.github.gcacace.signaturepad.views.SignaturePad;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/7/17 16:22
 */

public class HandWritingTestFragment extends BaseFragment {
  private static final int REQUEST_EXTERNAL_STORAGE = 1;
  private static String[] PERMISSIONS_STORAGE = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
  @BindView(R.id.signature_pad) SignaturePad mSignaturePad;
  //@BindView(R.id.signature_pad_description) TextView mSignaturePadDescription;
  //@BindView(R.id.signature_pad_container) RelativeLayout mSignaturePadContainer;
  @BindView(R.id.clear_button) Button mClearButton;
  @BindView(R.id.save_button) Button mSaveButton;
  //@BindView(R.id.buttons_container) LinearLayout mButtonsContainer;

  /**
   * Checks if the app has permission to write to device storage
   * <p/>
   * If the app does not has permission then the user will be prompted to grant permissions
   *
   * @param activity the activity from which permissions are checked
   */
  public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission =
        ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
      // We don't have permission so prompt the user
      ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_hand_writing_test, container, false);
    ButterKnife.bind(this, view);
    return view;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom("手写测试");
    verifyStoragePermissions(mActivity);
    mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
      @Override public void onStartSigning() {
        //Toast.makeText(mActivity, "OnStartSigning", Toast.LENGTH_SHORT).show();
      }

      @Override public void onSigned() {
        mSaveButton.setEnabled(true);
        mClearButton.setEnabled(true);
      }

      @Override public void onClear() {
        mSaveButton.setEnabled(false);
        mClearButton.setEnabled(false);
      }
    });

    mClearButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        mSignaturePad.clear();
      }
    });

    mSaveButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
        if (addJpgSignatureToGallery(signatureBitmap)) {
          Toast.makeText(mActivity, "保存到设备", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(mActivity, "保存失败", Toast.LENGTH_SHORT).show();
        }
        if (addSvgSignatureToGallery(mSignaturePad.getSignatureSvg())) {
          Toast.makeText(mActivity, "SVG 保存到设备", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(mActivity, "SVG 保存失败", Toast.LENGTH_SHORT).show();
        }
      }
    });
  }

  @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
      @NonNull int[] grantResults) {
    switch (requestCode) {
      case REQUEST_EXTERNAL_STORAGE: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
          Toast.makeText(mActivity, "权限被拒绝", Toast.LENGTH_SHORT).show();
        }
      }
    }
  }

  public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory.
    File file =
        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            albumName);
    if (!file.mkdirs()) {
      Log.e("SignaturePad", "Directory not created");
    }
    return file;
  }

  public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
    Bitmap newBitmap =
        Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(newBitmap);
    canvas.drawColor(Color.WHITE);
    canvas.drawBitmap(bitmap, 0, 0, null);
    OutputStream stream = new FileOutputStream(photo);
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
    stream.close();
  }

  public boolean addJpgSignatureToGallery(Bitmap signature) {
    boolean result = false;
    try {
      File photo = new File(getAlbumStorageDir("SignaturePad"),
          String.format("Signature_%d.jpg", System.currentTimeMillis()));
      saveBitmapToJPG(signature, photo);
      scanMediaFile(photo);
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }

  private void scanMediaFile(File photo) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(photo);
    mediaScanIntent.setData(contentUri);
    mActivity.sendBroadcast(mediaScanIntent);
  }

  public boolean addSvgSignatureToGallery(String signatureSvg) {
    boolean result = false;
    try {
      File svgFile = new File(getAlbumStorageDir("SignaturePad"),
          String.format("Signature_%d.svg", System.currentTimeMillis()));
      OutputStream stream = new FileOutputStream(svgFile);
      OutputStreamWriter writer = new OutputStreamWriter(stream);
      writer.write(signatureSvg);
      writer.close();
      stream.flush();
      stream.close();
      scanMediaFile(svgFile);
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
}
